﻿/*
 * MqttSend, a javascript background or console sender.
 *
 * Copyright (c) 2021, LearningPawn5
 * All rights reserved.
 *
 * Need
 * jQuery.js, jQuery.cookie.js, mqttws31.js, etc.
 */
var hostname = 'broker.hivemq.com', port = 8000, clientId = $.cookie("SESSIONID"), timeout = 5, keepAlive = 50, cleanSession = false, ssl = false, userName = 'admin';
password = 'password', subscribe_topic = "fjjxu/19/device/#", publish_topic = "fjjxu/19/device/";
client = new Paho.MQTT.Client(hostname, port, clientId);
var options = {
	invocationContext : {
		host : hostname,
		port : port,
		path : client.path,
		clientId : clientId
	},
	timeout : timeout,
	keepAliveInterval : keepAlive,
	cleanSession : cleanSession,
	useSSL : ssl,
	userName : userName,
	password : password,
	onSuccess : onConnect,
	onFailure : function(e) {
		$("#statusbar").attr("class", "alert alert-warning");
		$("#statusbar").text("连接MQTT服务器失败！ ");
	}
};
function onConnect() {
	$("#statusbar").attr("class", "alert alert-info");
	$("#statusbar").text("连接MQTT服务器成功！ ");
	client.subscribe(subscribe_topic, {
		qos : 0
	});
	console.log("MQTT主题 "+subscribe_topic+" 订阅成功！");//此处为订阅
}
client.onConnectionLost = onConnectionLost;
//注册连接断开处理事件
client.onMessageArrived = onMessageArrived;
//注册消息接收处理事件
function onConnectionLost(responseObject) {
	console.log(responseObject);
	if (responseObject.errorCode !== 0) {
		console.log("onConnectionLost:" + responseObject.errorMessage);
		$("#statusbar").attr("class", "alert alert-warning");
		$("#statusbar").text("与MQTT服务器连接已断开！ ");
	}
}
function onMessageArrived(message) {
	//收到的消息在这里处理
	console.log("收到消息:" + message.payloadString);
	var datajson = JSON.parse(message.payloadString);
	var sendData = JSON.parse(JSON.stringify(datajson.data));
	$.ajax({
		type : "post",
		url : "HistoryDataServlet?action=add",
		data : sendData,
		dataType:"json", 
        contentType:"application/json;charset=utf-8", 
		success : function(data) {
			console.log("add OK. And msg: "+data);
		},
		error : function(result) {
			$("#statusbar").attr("class", "alert alert-warning");
			$("#statusbar").text("数据库服务器的消息发送意外中断！ ");
		}
	});
}
function mqttsend(type, dataJson) {
	var jsonRaw = {
		device: type,
		time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
		data: JSON.stringify(dataJson),
		clientId: clientId
	};
	message = new Paho.MQTT.Message(JSON.stringify(jsonRaw));
	message.destinationName = publish_topic + type;
	client.send(message);
}

//预置方法
Date.prototype.Format = function(fmt) {
	var o = {
		"M+" : this.getMonth() + 1, //月份
		"d+" : this.getDate(), //日
		"h+" : this.getHours(), //小时
		"m+" : this.getMinutes(), //分
		"s+" : this.getSeconds(), //秒
		"q+" : Math.floor((this.getMonth() + 3) / 3),
		"S" : this.getMilliseconds()
	//毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};

String.format = function() {
	var s = arguments[0];
	for (var i = 0; i < arguments.length - 1; i++) {
		var reg = new RegExp("\\{" + i + "\\}", "gm");
		s = s.replace(reg, arguments[i + 1]);
	}
	return s;
};